package com.bzm.config.im;

import java.util.HashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.Channel;

/**
 * @Description:用户id和channel的关联关系处理
 * @author hemiao
 * @time:2020年5月21日 下午10:57:30
 */
public class UserChannelRel {
	
	private static final Logger log = LoggerFactory.getLogger(UserChannelRel.class);
		
	private static HashMap<String, Channel> userMap = new HashMap<>();
	
	public static HashMap<String, Channel> getUserMap() {
		return userMap;
	}

	public static void put(String userId, Channel channel) {
		userMap.put(userId, channel);
	}
	
	public static Channel get(String userId) {
		return userMap.get(userId);
	}
	
	public static void remove(String userId) {
		userMap.remove(userId);
	}
	
	public static String removeChannelId(Channel channel,String msg) {
		String channelId = channel.id().asLongText();
		String userId = null;
		if(StringUtils.isNotBlank(channelId)) {
			for (HashMap.Entry<String, Channel> entry : userMap.entrySet()) {
				//String key = entry.getKey();
				Channel channelVal = entry.getValue();
				// entry.getValue().id().asLongText() 和   asShortText
				String id = channelVal.id().asLongText();
				if(id.equals(channelId)){	
					userId = entry.getKey();
					userMap.remove(userId);
					log.info(msg+" userId: " + userId + ", ChannelId: " + id);
					break;
				}
			}
		}
		return userId;
	}
	
	public static void output() {
		for (HashMap.Entry<String, Channel> entry : userMap.entrySet()) {
			Channel channelVal = entry.getValue();
			String id = channelVal.id().asLongText();
			log.info("连接程序-获得连接----output: UserId: " + entry.getKey() 
							+ ", ChannelId: " + id);
		}
	}
	
}
